package com.sbtr.config;

import io.swagger.annotations.ApiOperation;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.annotations.ApiIgnore;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import static springfox.documentation.builders.PathSelectors.regex;

@Configuration
@EnableSwagger2
@EnableConfigurationProperties(ApiInfoProperties.class)
public class SwaggerConfiguration {

	@Bean
	public Docket springfoxDocket(ApiInfoProperties apiInfo) {
		Docket docket = new Docket(DocumentationType.SWAGGER_2);
		docket.ignoredParameterTypes(ApiIgnore.class);
		docket.apiInfo(apiInfo(apiInfo));
		docket.pathMapping("/").select().paths(regex("^.*(?<!error)$")).build();
		// 下面这句代码是只生成被ApiOperation这个注解注解过的api接口
		// 以及最后一定要执行build()方法,不然不起作用
		docket.select().apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)).build();

		return docket;
	}

	@Bean
	ApiInfo apiInfo(ApiInfoProperties apiInfoProperties) {
//		Contact contact = apiInfoProperties.getContact();
		return new ApiInfoBuilder().title(apiInfoProperties.getTitle())
			.description(apiInfoProperties.getDescription()).version(apiInfoProperties.getVersion())
			.termsOfServiceUrl(apiInfoProperties.getTermsOfServiceUrl())
//			.contact(new springfox.documentation.service.Contact(contact.getName(), contact.getUrl(), contact.getEmail()))
			.license(apiInfoProperties.getLicense()).licenseUrl(apiInfoProperties.getLicenseUrl()).build();
	}
}
